<template>
  <div class="panel-tab__content">
    <!-- 属性表格 -->
    <t-table 
      :data="elementPropertyList" 
      :columns="columns"
      row-key="id"
      max-height="240"
      bordered
      size="small"
      stripe
      hover
    >
      <template #operation="{ row, rowIndex }">
        <t-space>
          <t-link size="small" @click="openAttributesForm(row, rowIndex)">
            编辑
          </t-link>
          <t-link
            size="small"
            theme="danger"
            @click="removeAttributes(row, rowIndex)"
          >
            移除
          </t-link>
        </t-space>
      </template>
    </t-table>

    <!-- 添加按钮 -->
    <div class="element-drawer__button">
      <t-button 
        theme="primary" 
        block
        size="small"
        @click="openAttributesForm(null, -1)"
      >
        <template #icon><add-icon /></template>
        添加属性
      </t-button>
    </div>

    <!-- 属性配置对话框 -->
    <t-dialog
      v-model:visible="propertyFormModelVisible"
      header="属性配置"
      width="600px"
      :footer="false"
      destroy-on-close
    >
      <t-form 
        :model="propertyForm" 
        label-width="120px" 
        ref="attributeFormRef"
        layout="inline"
      >
        <t-form-item 
          label="属性名" 
          name="name"
         
        >
          <t-input v-model:value="propertyForm.name" clearable placeholder="请输入属性名" />
        </t-form-item>

        <t-form-item 
          label="属性值" 
          name="value"
          
        >
          <t-input v-model:value="propertyForm.value" clearable placeholder="请输入属性值" />
        </t-form-item>

        <t-form-item style="margin-left: 120px">
          <t-space>
            <t-button @click="propertyFormModelVisible = false">取消</t-button>
            <t-button theme="primary" @click="saveAttribute">确定</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script lang="ts" setup>
import { AddIcon } from 'tdesign-icons-vue-next';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { inject, nextTick, ref, toRaw, watch } from 'vue';

defineOptions({ name: 'ElementProperties' });

const props = defineProps({
  id: String,
  type: String
});

const prefix = inject('prefix');

// 表格列配置
const columns = [
  { colKey: 'serial-number', title: '序号', width: 60 },
  { colKey: 'name', title: '属性名', ellipsis: true, minWidth: 120 },
  { colKey: 'value', title: '属性值', ellipsis: true, minWidth: 120 },
  { colKey: 'operation', title: '操作', width: 120, fixed: 'right' }
].map(column => ({ ...column, align: 'center' }));

// 数据相关
const elementPropertyList = ref<any[]>([]);
const propertyForm = ref<any>({});
const editingPropertyIndex = ref(-1);
const propertyFormModelVisible = ref(false);
const bpmnElement = ref();
const otherExtensionList = ref<any[]>([]);
const bpmnElementProperties = ref();
const bpmnElementPropertyList = ref<any[]>([]);
const attributeFormRef = ref();

// 获取BPMN实例
const bpmnInstances = () => (window as any)?.bpmnInstances;

// 重置属性列表
const resetAttributesList = () => {
  bpmnElement.value = bpmnInstances().bpmnElement;
  otherExtensionList.value = [];
  
  bpmnElementProperties.value = 
    bpmnElement.value.businessObject?.extensionElements?.values?.filter((ex: any) => {
      if (ex.$type !== `${prefix}:Properties`) {
        otherExtensionList.value.push(ex);
      }
      return ex.$type === `${prefix}:Properties`;
    }) ?? [];

  bpmnElementPropertyList.value = bpmnElementProperties.value.reduce(
    (pre: any[], current: any) => pre.concat(current.values),
    []
  );

  elementPropertyList.value = JSON.parse(JSON.stringify(bpmnElementPropertyList.value ?? []));
};

// 打开属性表单
const openAttributesForm = (attr: any, index: number) => {
  editingPropertyIndex.value = index;
  propertyForm.value = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
  propertyFormModelVisible.value = true;
  
  nextTick(() => {
    attributeFormRef.value?.clearValidate();
  });
};

// 移除属性
const removeAttributes = async (attr: any, index: number) => {
  const confirmDia = DialogPlugin({
    body: '确认移除该属性吗？',
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: () => {
      elementPropertyList.value.splice(index, 1);
      bpmnElementPropertyList.value.splice(index, 1);
      
      const propertiesObject = bpmnInstances().moddle.create(`${prefix}:Properties`, {
        values: bpmnElementPropertyList.value
      });
      
      updateElementExtensions(propertiesObject);
      resetAttributesList();
      MessagePlugin.success('移除成功');
      confirmDia.hide()
    },
    onClose: () => confirmDia.hide(),
  });
};

// 保存属性
const saveAttribute = async () => {
  const validateResult = await attributeFormRef.value.validate();
  if (validateResult !== true) return;

  const { name, value } = propertyForm.value;
  console.log(name,value,'pp');
  
  console.log(editingPropertyIndex.value ,'editingPropertyIndex.value ');
  
  if (editingPropertyIndex.value !== -1) {
    console.log(bpmnInstances().modeling,'kk');
    
    bpmnInstances().modeling.updateModdleProperties(
      toRaw(bpmnElement.value),
      toRaw(bpmnElementPropertyList.value)[toRaw(editingPropertyIndex.value)],
      {
        name,
        value
      }
    );
  } else {
    const newPropertyObject = bpmnInstances().moddle.create(`${prefix}:Property`, {
      name,
      value
    });
    
    const propertiesObject = bpmnInstances().moddle.create(`${prefix}:Properties`, {
      values: [...bpmnElementPropertyList.value, newPropertyObject]
    });
    console.log(propertiesObject,'2l');
    console.log(bpmnInstances().moddle,'ll');
    
    
    updateElementExtensions(propertiesObject);
  }

  propertyFormModelVisible.value = false;
  resetAttributesList();
  MessagePlugin.success('保存成功');
};

// 更新元素扩展
const updateElementExtensions = (properties: any) => {
  const extensions = bpmnInstances().moddle.create('bpmn:ExtensionElements', {
    values: otherExtensionList.value.concat([properties])
  });
  console.log(extensions,'extensions');
  
  console.log(bpmnInstances().modeling,'xxx');
  bpmnInstances().modeling.updateProperties(toRaw(bpmnElement.value), {
    extensionElements: extensions
  })
  
};

// 监听ID变化
watch(
  () => props.id,
  (val) => val && val.length && resetAttributesList(),
  { immediate: true }
);
</script>

<style scoped>
.element-drawer__button {
  margin-top: 16px;
  text-align: center;
}
</style>